<template>
  <div class="editor-container">
    <!-- 左侧参数设置区 -->
    <div class="params-section">
      <div class="params-card">
        <h3 class="params-title">文章参数</h3>
        <el-form :model="articleParams" label-width="80px">
          <el-form-item label="标题">
            <el-input 
              v-model="articleParams.title" 
              placeholder="请输入文章标题"
              size="large"
            />
          </el-form-item>
          
          <el-form-item label="写作模板">
            <el-select 
              v-model="articleParams.templateId" 
              placeholder="选择写作提示词模板" 
              class="full-width"
              @change="handleArticleTemplateChange"
              clearable
            >
              <el-option-group label="文章写作">
                <el-option 
                  v-for="template in articleTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
              <el-option-group label="其他模板">
                <el-option 
                  v-for="template in otherTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
            </el-select>
            <div class="form-tip" v-if="articleParams.templateId">
              使用模板：{{ getTemplateName(articleParams.templateId) }}
            </div>
          </el-form-item>
          
          <template v-if="selectedArticleTemplate && selectedArticleTemplate.variables.length > 0">
            <el-divider content-position="center">模板变量</el-divider>
            
            <div v-if="hasSpecialVariables" class="special-variables-info">
              <el-alert
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>模板将自动使用以下信息（如果提供）：</p>
                  <ul class="special-vars-list">
                    <li v-if="hasSpecialVariable('_title')">
                      <strong>文章标题：</strong> {{ articleParams.title || '未提供' }}
                    </li>
                    <li v-if="hasSpecialVariable('_references')">
                      <strong>参考内容：</strong> 
                      {{ referenceContents.filter(ref => ref && ref.title && ref.content).length > 0 ? 
                        `${referenceContents.filter(ref => ref && ref.title && ref.content).length} 个参考链接` : 
                        '未提供' }}
                    </li>
                    <li v-if="hasSpecialVariable('_sample')">
                      <strong>用户样本：</strong> 
                      {{ vditor && vditor.getValue() ? '编辑器中的当前内容' : '未提供' }}
                    </li>
                  </ul>
                </template>
              </el-alert>
            </div>
            
            <el-form-item 
              v-for="variable in regularVariables" 
              :key="variable.name"
              :label="variable.description || variable.name"
            >
              <el-input 
                v-model="articleTemplateVariables[variable.name]" 
                :placeholder="variable.default_value || ''"
                :type="variable.name.includes('content') ? 'textarea' : 'text'"
                :rows="variable.name.includes('content') ? 3 : 1"
              />
            </el-form-item>
          </template>
          
          <el-form-item label="参考链接">
            <div v-for="(ref, index) in articleParams.references" :key="index" class="reference-item">
              <el-input 
                v-model="articleParams.references[index]" 
                placeholder="请输入参考链接"
                size="default"
              >
                <template #append>
                  <el-button-group>
                    <el-button 
                      @click="fetchReference(index)" 
                      type="primary"
                      :icon="Download"
                      :loading="fetchingReference === index"
                      title="抓取内容"
                    />
                    <el-button 
                      v-if="referenceContents[index]"
                      @click="previewReference(index)" 
                      type="info"
                      :icon="View"
                      title="预览内容"
                    />
                    <el-button 
                      v-if="referenceContents[index]"
                      @click="useReferenceTitle(index)" 
                      type="success"
                      :icon="Edit"
                      title="使用此标题"
                    />
                    <el-button 
                      @click="removeReference(index)" 
                      :disabled="articleParams.references.length <= 1"
                      type="danger"
                      :icon="Delete"
                      title="删除链接"
                    />
                  </el-button-group>
                </template>
              </el-input>
            </div>
            <el-button 
              @click="addReference" 
              :disabled="articleParams.references.length >= 5"
              type="primary"
              plain
              class="add-reference-btn"
            >
              <el-icon><Plus /></el-icon>
              添加参考链接
            </el-button>
          </el-form-item>
          
          <el-form-item label="参考文本">
            <el-input
              v-model="articleParams.referenceContent"
              type="textarea"
              :rows="4"
              placeholder="请输入参考材料，AI 会参考这些内容进行写作"
            />
          </el-form-item>
          
          <el-form-item label="文章长度">
            <el-select 
              v-model="articleParams.length"
              class="full-width"
              size="default"
              clearable
              placeholder="选择文章长度（可选）"
            >
              <el-option label="短文 (500字以内)" value="short" />
              <el-option label="中等 (1000字左右)" value="medium" />
              <el-option label="长文 (2000字以上)" value="long" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="写作风格">
            <el-select 
              v-model="articleParams.style"
              class="full-width"
              size="default"
              clearable
              placeholder="选择写作风格（可选）"
            >
              <el-option label="专业严谨" value="professional" />
              <el-option label="轻松活泼" value="casual" />
              <el-option label="故事化" value="storytelling" />
              <el-option label="技术性" value="technical" />
              <el-option label="教育性" value="educational" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="generateContent" 
              :loading="generating"
              size="large"
              class="generate-btn"
            >
              {{ isEdit ? '重新生成' : '生成文章' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- AI 辅助功能区 -->
      <div class="params-card ai-tools-card">
        <h3 class="params-title">AI 辅助工具</h3>
        
        <!-- AI 模型选择 -->
        <el-form label-width="80px">
          <el-form-item label="AI 模型">
            <el-select v-model="selectedModelId" placeholder="选择 AI 模型" class="full-width">
              <el-option
                v-for="model in aiModels"
                :key="model.id"
                :label="model.name"
                :value="model.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        
        <!-- AI 工具按钮组 -->
        <div class="ai-tools-buttons">
          <el-button type="primary" @click="handleAICommand('continue')" :icon="Edit">
            续写内容
          </el-button>
          <el-button type="success" @click="handleAICommand('improve')" :icon="Star">
            优化内容
          </el-button>
          <el-button type="warning" @click="handleAICommand('summarize')" :icon="Document">
            生成摘要
          </el-button>
          <el-button type="info" @click="handleAICommand('custom')" :icon="Setting">
            自定义指令
          </el-button>
          <el-button @click="handleAICommand('templates')" :icon="Collection">
            使用模板
          </el-button>
        </div>
      </div>
    </div>

    <!-- 右侧编辑器区域 -->
    <div class="content-section">
      <div class="editor-header">
        <h3 class="editor-title">{{ isEdit ? '编辑文章' : '创建文章' }}</h3>
        <div class="editor-actions">
          <el-button 
            type="success" 
            @click="saveDraft" 
            :loading="savingDraft"
            size="small"
          >
            保存草稿
          </el-button>
          <el-button 
            type="primary" 
            @click="publishArticleHandler" 
            :loading="saving"
            size="small"
          >
            发布文章
          </el-button>
        </div>
      </div>
      
      <!-- 始终保留 vditor 容器，但在加载时添加遮罩 -->
      <div id="vditor" class="vditor-container"></div>
      
      <!-- 使用绝对定位的加载遮罩 -->
      <div v-if="loading" class="editor-loading-overlay">
        <el-skeleton :rows="10" animated />
      </div>
    </div>
    
    <!-- AI 生成对话框 -->
    <el-dialog
      v-model="aiDialogVisible"
      :title="aiDialogTitle"
      width="800px"
    >
      <div v-if="aiDialogMode === 'generate'">
        <el-form label-width="100px">
          <el-form-item label="标题">
            <el-input v-model="aiParams.title" placeholder="请输入文章标题" />
          </el-form-item>
          <el-form-item label="风格">
            <el-select v-model="aiParams.style" placeholder="选择文章风格" style="width: 100%">
              <el-option label="专业学术" value="academic" />
              <el-option label="新闻报道" value="news" />
              <el-option label="博客随笔" value="blog" />
              <el-option label="科普教育" value="educational" />
              <el-option label="营销推广" value="marketing" />
            </el-select>
          </el-form-item>
          <el-form-item label="字数">
            <el-input-number v-model="aiParams.wordCount" :min="100" :max="3000" :step="100" />
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="aiDialogMode === 'continue' || aiDialogMode === 'improve'">
        <el-form label-width="100px">
          <el-form-item label="选定内容">
            <el-input
              type="textarea"
              v-model="aiParams.selectedText"
              :rows="5"
              placeholder="当前选中的内容"
              disabled
            />
          </el-form-item>
          <el-form-item label="指令">
            <el-input
              type="textarea"
              v-model="aiParams.instruction"
              :rows="3"
              :placeholder="aiDialogMode === 'continue' ? '请输入续写指令，例如：继续展开论述...' : '请输入优化指令，例如：使语言更生动...'"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="aiDialogMode === 'summarize'">
        <el-form label-width="100px">
          <el-form-item label="摘要长度">
            <el-select v-model="aiParams.summaryLength" placeholder="选择摘要长度" style="width: 100%">
              <el-option label="简短 (50字左右)" value="short" />
              <el-option label="中等 (100字左右)" value="medium" />
              <el-option label="详细 (200字左右)" value="long" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="aiDialogMode === 'custom'">
        <el-form label-width="100px">
          <el-form-item label="自定义指令">
            <el-input
              type="textarea"
              v-model="aiParams.customPrompt"
              :rows="5"
              placeholder="请输入自定义指令，例如：将这段内容改写成对话形式..."
            />
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="aiDialogMode === 'templates'">
        <el-form label-width="100px">
          <el-form-item label="选择模板">
            <el-select v-model="aiParams.templateId" placeholder="选择提示词模板" style="width: 100%" @change="handleTemplateChange">
              <el-option-group label="文章写作">
                <el-option 
                  v-for="template in articleTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
              <el-option-group label="内容优化">
                <el-option 
                  v-for="template in optimizationTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
              <el-option-group label="摘要生成">
                <el-option 
                  v-for="template in summaryTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
              <el-option-group label="其他">
                <el-option 
                  v-for="template in otherTemplates" 
                  :key="template.id" 
                  :label="template.name" 
                  :value="template.id" 
                />
              </el-option-group>
            </el-select>
          </el-form-item>
          
          <!-- 模板变量 -->
          <template v-if="currentTemplate && currentTemplate.variables.length > 0">
            <el-form-item 
              v-for="variable in currentTemplate.variables" 
              :key="variable.name"
              :label="variable.description || variable.name"
            >
              <el-input 
                v-model="templateVariables[variable.name]" 
                :placeholder="variable.default_value || ''"
                :type="variable.name.includes('content') ? 'textarea' : 'text'"
                :rows="variable.name.includes('content') ? 4 : 1"
              />
            </el-form-item>
          </template>
        </el-form>
      </div>
      
      <!-- AI 生成结果 -->
      <div v-if="aiGenerating" class="ai-generating">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="aiResult" class="ai-result">
        <h4>AI 生成结果</h4>
        <div class="ai-content">
          <pre>{{ aiResult }}</pre>
        </div>
        <div class="ai-actions">
          <el-button type="primary" @click="insertAIResult">插入到编辑器</el-button>
          <el-button @click="regenerateContent">重新生成</el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="aiDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="generateWithAI" :loading="aiGenerating" :disabled="!canGenerate">
            生成
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 参考内容对话框 -->
    <el-dialog
      v-model="referenceDialogVisible"
      title="参考内容预览"
      width="800px"
    >
      <div v-if="currentReference">
        <h3>{{ currentReference.title }}</h3>
        <p v-if="currentReference.author || currentReference.account" class="reference-meta">
          {{ currentReference.author }} {{ currentReference.account ? `(${currentReference.account})` : '' }}
        </p>
        <p class="reference-url">
          <a :href="currentReference.url" target="_blank">{{ currentReference.url }}</a>
        </p>
        
        <el-divider />
        
        <div class="reference-content">
          <pre>{{ currentReference.content }}</pre>
        </div>
        
        <div class="dialog-footer">
          <el-button @click="referenceDialogVisible = false">关闭</el-button>
          <el-button type="warning" @click="cleanReferenceContent" :loading="cleaningContent">
            AI 清理内容
          </el-button>
          <el-button type="primary" @click="useReferenceAsPrompt">
            作为参考使用
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, ArrowDown, Star, Edit, Document, Setting, Collection, Download, View } from '@element-plus/icons-vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { generateArticle, fetchArticle, saveArticle, publishArticle, fetchReferenceContent, generateArticleContent, generateArticleContentStream } from '../api/article'
import { fetchAIModels } from '../api/ai_model'
import { fetchPromptTemplates, processPromptTemplate } from '../api/prompt_template'

const route = useRoute()
const router = useRouter()
const isEdit = ref(false)
const initialContent = ref('')
const lastSaveTime = ref(null)
const loading = ref(false)

const articleParams = ref({
  title: '',
  references: [''],
  referenceContent: '',
  length: '',
  style: '',
  templateId: ''
})

const generating = ref(false)
const saving = ref(false)
const savingDraft = ref(false)
let vditor = null

const aiDialogVisible = ref(false)
const aiDialogMode = ref('')
const aiDialogTitle = ref('')
const aiParams = ref({
  title: '',
  style: '',
  wordCount: 800,
  selectedText: '',
  instruction: '',
  summaryLength: 'medium',
  customPrompt: '',
  templateId: ''
})
const aiGenerating = ref(false)
const aiResult = ref('')
const aiModels = ref([])
const selectedModelId = ref('')
const editorInstance = ref(null)

const promptTemplates = ref([])
const currentTemplate = ref(null)
const templateVariables = ref({})

const articleTemplates = computed(() => 
  promptTemplates.value.filter(t => t.category === 'article')
)
const optimizationTemplates = computed(() => 
  promptTemplates.value.filter(t => t.category === 'optimization')
)
const summaryTemplates = computed(() => 
  promptTemplates.value.filter(t => t.category === 'summary')
)
const otherTemplates = computed(() => 
  promptTemplates.value.filter(t => t.category !== 'article' && t.category !== 'optimization' && t.category !== 'summary')
)

const canGenerate = computed(() => {
  if (!selectedModelId.value) return false
  
  switch (aiDialogMode.value) {
    case 'generate':
      return !!aiParams.value.title
    case 'continue':
    case 'improve':
      return !!aiParams.value.selectedText
    case 'summarize':
      return true
    case 'custom':
      return !!aiParams.value.customPrompt
    case 'templates':
      return !!aiParams.value.templateId
    default:
      return false
  }
})

const addReference = () => {
  if (articleParams.value.references.length < 5) {
    articleParams.value.references.push('')
  }
}

const removeReference = (index) => {
  articleParams.value.references.splice(index, 1)
}

const articleTemplateVariables = reactive({})

const getTemplateName = (templateId) => {
  const template = promptTemplates.value.find(t => t.id === templateId)
  return template ? template.name : ''
}

const hasSpecialVariables = computed(() => {
  if (!selectedArticleTemplate.value || !selectedArticleTemplate.value.variables) {
    return false
  }
  
  // 只检查三种特殊变量：标题、参考内容、用户样本
  return selectedArticleTemplate.value.variables.some(v => 
    v.name === '_title' || 
    v.name === '_references' || 
    v.name === '_sample'
  )
})

const specialVariables = computed(() => {
  if (!selectedArticleTemplate.value || !selectedArticleTemplate.value.variables) {
    return []
  }
  
  // 只返回三种特殊变量
  return selectedArticleTemplate.value.variables.filter(v => 
    v.name === '_title' || 
    v.name === '_references' || 
    v.name === '_sample'
  )
})

const regularVariables = computed(() => {
  if (!selectedArticleTemplate.value || !selectedArticleTemplate.value.variables) {
    return []
  }
  
  // 返回所有非特殊变量
  return selectedArticleTemplate.value.variables.filter(v => 
    !v.name.startsWith('_') || 
    (v.name !== '_title' && 
     v.name !== '_references' && 
     v.name !== '_sample')
  )
})

const getSpecialVariableLabel = (name) => {
  switch (name) {
    case '_title':
      return '文章标题'
    case '_references':
      return '参考内容'
    case '_sample':
      return '用户样本'
    default:
      return name
  }
}

const handleArticleTemplateChange = async (templateId) => {
  if (!templateId) {
    selectedArticleTemplate.value = null
    return
  }
  
  // 查找选中的模板
  const allTemplates = [...articleTemplates.value, ...otherTemplates.value]
  selectedArticleTemplate.value = allTemplates.find(t => t.id === templateId)
  
  // 初始化模板变量
  if (selectedArticleTemplate.value) {
    // 重置变量值
    articleTemplateVariables.value = {}
    
    // 为每个非特殊变量设置默认值
    selectedArticleTemplate.value.variables.forEach(variable => {
      if (!variable.name.startsWith('_')) {
        articleTemplateVariables.value[variable.name] = variable.default_value || ''
      }
    })
  }
}

const articleContent = ref('')

const fetchingReference = ref(null)
const referenceDialogVisible = ref(false)
const currentReference = ref(null)
const referenceContents = ref([])

const cleaningContent = ref(false)

const fetchReference = async (index) => {
  const url = articleParams.value.references[index]
  if (!url) {
    ElMessage.warning('请输入有效的链接')
    return
  }
  
  try {
    fetchingReference.value = index
    const result = await fetchReferenceContent(url)
    
    // 保存参考内容
    referenceContents.value[index] = result
    
    // 显示参考内容对话框
    currentReference.value = result
    referenceDialogVisible.value = true
    
    ElMessage.success('成功抓取参考内容')
  } catch (error) {
    console.error('抓取参考内容失败', error)
    ElMessage.error('抓取参考内容失败: ' + error.message)
  } finally {
    fetchingReference.value = null
  }
}

const cleanReferenceContent = async () => {
  if (!currentReference.value) return
  
  try {
    cleaningContent.value = true
    
    // 调用 AI 模型清理内容
    const result = await generateArticleContent({
      model_id: selectedModelId.value,
      system_prompt: "你是一个专业的内容编辑，擅长清理网页抓取的文章内容。请去除所有广告、推广、无关的内容，保留文章的核心内容。保持文章的结构和格式，使其更加清晰易读。",
      user_prompt: `请清理以下抓取的文章内容，去除所有广告、推广和无关内容，只保留有价值的核心内容：\n\n标题：${currentReference.value.title}\n\n${currentReference.value.content}`
    })
    
    // 更新参考内容
    currentReference.value.content = result.content
    
    // 同时更新保存的参考内容
    const index = articleParams.value.references.findIndex(ref => ref === currentReference.value.url)
    if (index !== -1) {
      referenceContents.value[index] = currentReference.value
    }
    
    ElMessage.success('内容已清理')
  } catch (error) {
    console.error('清理内容失败', error)
    ElMessage.error('清理内容失败: ' + error.message)
  } finally {
    cleaningContent.value = false
  }
}

const useReferenceAsPrompt = () => {
  if (!currentReference.value) return
  
  // 将当前参考内容标记为已使用
  const index = articleParams.value.references.findIndex(ref => ref === currentReference.value.url)
  if (index !== -1) {
    // 确保 referenceContents 数组中有这个索引位置
    if (!referenceContents.value[index]) {
      referenceContents.value[index] = currentReference.value
    }
  }
  
  // 关闭对话框
  referenceDialogVisible.value = false
  
  ElMessage.success('参考内容已添加到生成提示中')
}

const generateContent = async () => {
  if (!articleParams.value.title) {
    ElMessage.warning('请输入文章标题')
    return
  }
  
  try {
    generating.value = true
    
    let systemPrompt = ''
    let userPrompt = ''
    
    if (articleParams.value.templateId && selectedArticleTemplate.value) {
      try {
        console.log('Selected template:', selectedArticleTemplate.value);
        
        // 准备特殊变量，只包含三种特殊变量，并且只有在用户提供了相应内容时才添加
        const specialVariables = {}
        
        // 文章标题
        if (articleParams.value.title) {
          specialVariables['_title'] = articleParams.value.title
        }
        
        // 参考内容
        const validReferences = referenceContents.value.filter(ref => ref && ref.title && ref.content)
        if (validReferences.length > 0) {
          specialVariables['_references'] = validReferences
        }
        
        // 用户样本
        const editorContent = vditor.getValue()
        if (editorContent) {
          specialVariables['_sample'] = editorContent
        }
        
        console.log('Special variables:', specialVariables);
        
        // 合并普通变量和特殊变量
        const allVariables = {}
        
        // 处理普通变量
        Object.keys(articleTemplateVariables).forEach(key => {
          allVariables[key] = articleTemplateVariables[key] || ''
        })
        
        // 添加特殊变量
        Object.keys(specialVariables).forEach(key => {
          allVariables[key] = specialVariables[key]
        })
        
        console.log('All variables (before processing):', allVariables);
        
        // 检查 _references 变量的格式
        if (allVariables._references) {
          console.log('_references type:', typeof allVariables._references);
          console.log('_references is array:', Array.isArray(allVariables._references));
          console.log('_references length:', allVariables._references.length);
          if (allVariables._references.length > 0) {
            console.log('First reference item:', allVariables._references[0]);
          }
        }
        
        try {
          const processedTemplate = await processPromptTemplate(
            articleParams.value.templateId, 
            allVariables
          )
          
          console.log('Processed template:', processedTemplate);
          
          systemPrompt = processedTemplate.system_prompt
          userPrompt = processedTemplate.user_prompt
        } catch (error) {
          console.error('处理模板失败:', error);
          console.error('Error details:', error.response?.data);
          ElMessage.error('处理模板失败: ' + error.message);
          generating.value = false;
          return;
        }
      } catch (error) {
        console.error('处理模板失败:', error);
        ElMessage.error('处理模板失败: ' + error.message);
        generating.value = false;
        return;
      }
    } else {
      // 使用默认提示词
      systemPrompt = `你是一位专业的内容创作者，擅长撰写高质量的文章。`
      
      // 构建用户提示词，只包含必要的参数
      let promptParts = [
        `请为我写一篇关于"${articleParams.value.title}"的文章，要求：`,
        '1. 内容丰富、结构清晰',
        '2. 语言流畅自然'
      ];
      
      // 只有当长度参数有值时才添加
      if (articleParams.value.length) {
        let lengthText = '';
        switch(articleParams.value.length) {
          case 'short':
            lengthText = '短文（500字以内）';
            break;
          case 'medium':
            lengthText = '中等长度（1000字左右）';
            break;
          case 'long':
            lengthText = '长文（2000字以上）';
            break;
          default:
            lengthText = '';
        }
        
        if (lengthText) {
          promptParts.push(`3. 文章长度：${lengthText}`);
        }
      }
      
      // 只有当风格参数有值时才添加
      if (articleParams.value.style) {
        let styleText = '';
        switch(articleParams.value.style) {
          case 'professional':
            styleText = '专业严谨';
            break;
          case 'casual':
            styleText = '轻松活泼';
            break;
          case 'storytelling':
            styleText = '故事化';
            break;
          case 'technical':
            styleText = '技术性';
            break;
          case 'educational':
            styleText = '教育性';
            break;
          default:
            styleText = '';
        }
        
        if (styleText) {
          promptParts.push(`${promptParts.length}. 写作风格：${styleText}`);
        }
      }
      
      // 添加Markdown格式要求
      promptParts.push(`${promptParts.length}. 使用Markdown格式`);
      
      // 合并提示词部分
      userPrompt = promptParts.join('\n');
      
      // 智能处理参考文本
      let referenceText = ''
      
      // 处理参考材料
      if (articleParams.value.referenceContent) {
        referenceText += `参考材料：\n${articleParams.value.referenceContent}\n\n`
      }
      
      // 处理参考链接内容
      if (referenceContents.value.length > 0) {
        referenceContents.value.forEach((ref, index) => {
          if (!ref || !ref.title || !ref.content) return
          
          // 限制内容长度
          const maxContentLength = 1500
          let contentPreview = ref.content
          if (contentPreview.length > maxContentLength) {
            // 截取前1500个字符，并尝试在句子结束处截断
            const truncated = contentPreview.substring(0, maxContentLength)
            const lastPeriod = truncated.lastIndexOf('。')
            if (lastPeriod > maxContentLength * 0.8) { // 如果句号位置在80%以后，就在句号处截断
              contentPreview = truncated.substring(0, lastPeriod + 1) + "..."
            } else {
              contentPreview = truncated + "..."
            }
          }
          
          // 只添加标题和内容，不添加链接
          referenceText += `参考资料 ${index + 1}：${ref.title}\n${contentPreview}\n\n`
        })
      }
      
      // 在用户提示词中添加参考内容
      if (referenceText) {
        userPrompt += '\n\n' + referenceText
      }
    }
    
    vditor.setValue('')
    
    let generatedContent = ''
    
    generateArticleContentStream(
      {
        model_id: selectedModelId.value,
        system_prompt: systemPrompt,
        user_prompt: userPrompt
      },
      (chunk) => {
        generatedContent += chunk
        vditor.setValue(generatedContent)
        const editorElement = document.querySelector('.vditor-ir pre.vditor-reset')
        if (editorElement) {
          editorElement.scrollTop = editorElement.scrollHeight
        }
      },
      () => {
        generating.value = false
        articleContent.value = generatedContent
        ElMessage.success('文章生成成功')
      },
      (error) => {
        generating.value = false
        console.error('生成文章失败', error)
        ElMessage.error('生成文章失败: ' + error.message)
      }
    )
  } catch (error) {
    generating.value = false
    console.error('生成文章失败', error)
    ElMessage.error('生成文章失败: ' + error.message)
  }
}

const loadArticle = async (id) => {
  try {
    loading.value = true
    
    // 获取文章数据
    const article = await fetchArticle(id)
    
    // 更新文章参数
    articleParams.value = {
      title: article.title,
      content: article.content,
      status: article.status,
      templateId: article.template_id,
      references: article.references || [''],
      referenceContent: article.reference_content || '',
      referenceStyle: article.reference_style || 'quote',
      length: article.length || 'medium',
      style: article.style || 'professional'
    }
    
    // 保存初始内容
    initialContent.value = article.content || ''
    
    // 等待编辑器初始化完成
    if (!vditor) {
      console.log('编辑器尚未初始化，等待初始化...')
      await initVditor()
    }
    
    // 设置编辑器内容
    if (vditor) {
      console.log('设置编辑器内容:', initialContent.value)
      // 使用 setTimeout 确保编辑器已完全初始化
      setTimeout(() => {
        vditor.setValue(initialContent.value)
      }, 100)
    } else {
      console.error('编辑器初始化失败')
    }
    
    ElMessage.success('文章加载成功')
  } catch (err) {
    console.error('加载文章失败', err)
    ElMessage.error('加载文章失败: ' + (err.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const initVditor = () => {
  return new Promise((resolve) => {
    if (vditor) {
      resolve(vditor)
      return
    }
    
    // 确保 DOM 元素存在
    const editorElement = document.getElementById('vditor')
    if (!editorElement) {
      console.error('找不到编辑器 DOM 元素')
      setTimeout(() => initVditor().then(resolve), 100)
      return
    }
    
    console.log('开始初始化编辑器')
    vditor = new Vditor('vditor', {
      height: '100%',
      mode: 'sv',
      toolbar: [
        'headings',
        'bold',
        'italic',
        'strike',
        'link',
        '|',
        'list',
        'ordered-list',
        'check',
        'outdent',
        'indent',
        '|',
        'quote',
        'line',
        'code',
        'inline-code',
        'table',
        '|',
        'undo',
        'redo',
        '|',
        'fullscreen',
        'preview',
        'image'
      ],
      placeholder: '开始写作...',
      preview: {
        delay: 500,
        hljs: {
          enable: true,
          style: 'github'
        },
        markdown: {
          // 启用图片预览
          linkify: true,
          autoSpace: true,
          fixTermTypo: true,
          toc: true,
          paragraphBeginningSpace: true,
          sanitize: false // 不过滤 HTML 标签，允许图片显示
        },
        math: {
          // 启用数学公式
          engine: 'KaTeX',
          inlineDigit: true,
          macros: {}
        }
      },
      upload: {
        accept: 'image/*',
        multiple: true,
        // 支持粘贴上传
        pasteImage: true,
        // 支持拖拽上传
        dropImage: true,
        // 上传接口
        url: '/api/upload/image',
        // 自定义上传参数
        fieldName: 'file',
        // 确保图片以 Markdown 格式插入
        linkToImgUrl: true,
        // 上传成功回调
        success: (editor, res) => {
          console.log('上传成功:', res)
          // 如果上传成功，Vditor 会自动将图片插入到编辑器中
        },
        // 上传失败回调
        error: (msg) => {
          console.error('上传失败:', msg)
          ElMessage.error(`图片上传失败: ${msg}`)
        },
        // 格式化上传响应结果
        format: (file, response) => {
          console.log('格式化上传响应:', file, response)
          try {
            // 解析响应数据
            const res = typeof response === 'string' ? JSON.parse(response) : response
            if (res.code === 0 && res.data && res.data.succMap) {
              // 返回图片URL，Vditor 会自动将其插入到编辑器中
              const url = res.data.succMap[file.name]
              console.log('提取的图片URL:', url)
              return url
            }
            console.error('无法从响应中提取图片URL:', res)
            return null
          } catch (error) {
            console.error('解析上传响应失败:', error)
            return null
          }
        }
      },
      // 图片配置
      image: {
        isPreview: true, // 是否预览图片
        preview: (bom) => {
          // 图片预览处理函数
          console.log('图片预览:', bom)
        }
      },
      // 启用粘贴时自动上传图片
      options: {
        enablePasteImage: true
      },
      after: () => {
        console.log('编辑器初始化完成')
        
        // 如果是编辑模式且有初始内容，设置编辑器内容
        if (isEdit.value && initialContent.value) {
          console.log('设置初始内容:', initialContent.value)
          vditor.setValue(initialContent.value)
        }
        
        resolve(vditor)
      }
    })
  })
}

const saveDraft = async () => {
  if (!articleParams.value.title) {
    ElMessage.warning('请输入文章标题')
    return
  }
  
  try {
    // 获取编辑器内容
    const content = vditor ? vditor.getValue() : ''
    
    // 准备文章数据
    const articleData = {
      title: articleParams.value.title,
      content: content,
      status: 'draft', // 设置状态为草稿
      template_id: articleParams.value.templateId,
      references: articleParams.value.references,
      reference_content: articleParams.value.referenceContent,
      reference_style: articleParams.value.referenceStyle,
      length: articleParams.value.length,
      style: articleParams.value.style
    }
    
    // 如果是编辑模式，添加文章ID
    if (isEdit.value) {
      articleData.id = route.params.id
    }
    
    // 保存文章
    const savedArticle = await saveArticle(articleData)
    
    // 更新最后保存时间
    lastSaveTime.value = new Date()
    
    ElMessage.success('草稿保存成功')
    
    // 如果是新建文章，保存后更新为编辑模式，但不导航
    if (!isEdit.value && savedArticle.id) {
      isEdit.value = true
      // 更新 URL，但不触发导航
      window.history.replaceState(
        null, 
        '', 
        `/articles/${savedArticle.id}/edit`
      )
    }
    
    return savedArticle
  } catch (err) {
    console.error('保存草稿失败', err)
    ElMessage.error('保存草稿失败: ' + (err.message || '未知错误'))
    throw err
  }
}

const publishArticleHandler = async () => {
  if (!articleParams.value.title) {
    ElMessage.warning('请输入文章标题')
    return
  }
  
  try {
    // 先保存草稿
    const draft = await saveDraft()
    if (!draft) return
    
    // 确认发布
    await ElMessageBox.confirm(
      '发布后的文章将对所有用户可见，确定要发布吗？',
      '发布确认',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    saving.value = true
    
    // 发布文章
    if (isEdit.value) {
      await publishArticle(route.params.id)
    } else if (draft.id) {
      await publishArticle(draft.id)
    }
    
    ElMessage.success('文章已发布')
    
    // 跳转到文章列表页
    router.push('/articles')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布文章失败:', error)
      ElMessage.error('发布文章失败: ' + (error.response?.data?.detail || error.message))
    }
  } finally {
    saving.value = false
  }
}

let autoSaveTimer = null

const startAutoSave = () => {
  autoSaveTimer = setInterval(async () => {
    if (route.params.id) {
      await saveDraft()
    }
  }, 30000)
}

const handleAICommand = (command) => {
  aiDialogMode.value = command
  aiResult.value = ''
  
  switch (command) {
    case 'generate':
      aiDialogTitle.value = '使用 AI 生成文章'
      break
    case 'continue':
      aiDialogTitle.value = '使用 AI 续写内容'
      aiParams.value.selectedText = getSelectedText()
      break
    case 'improve':
      aiDialogTitle.value = '使用 AI 优化内容'
      aiParams.value.selectedText = getSelectedText()
      break
    case 'summarize':
      aiDialogTitle.value = '使用 AI 生成摘要'
      break
    case 'custom':
      aiDialogTitle.value = '自定义 AI 指令'
      break
    case 'templates':
      aiDialogTitle.value = '使用提示词模板'
      break
  }
  
  aiDialogVisible.value = true
}

const getSelectedText = () => {
  if (editorInstance.value) {
    return editorInstance.value.selection.getContent({ format: 'text' }) || ''
  }
  return ''
}

const handleTemplateChange = async (templateId) => {
  templateVariables.value = {}
  
  currentTemplate.value = promptTemplates.value.find(t => t.id === templateId)
  
  if (currentTemplate.value && currentTemplate.value.variables) {
    currentTemplate.value.variables.forEach(variable => {
      if (variable.default_value) {
        templateVariables.value[variable.name] = variable.default_value
      }
    })
  }
}

const generateWithAI = async () => {
  if (!selectedModelId.value) {
    ElMessage.warning('请选择 AI 模型')
    return
  }
  
  try {
    aiGenerating.value = true
    
    let prompt = ''
    let systemPrompt = ''
    
    switch (aiDialogMode.value) {
      case 'generate':
        prompt = `请写一篇关于"${aiParams.value.title}"的文章，风格为${aiParams.value.style || '专业'}，字数大约${aiParams.value.wordCount}字。`
        systemPrompt = '你是一位专业的文章撰写者，擅长创作高质量的原创内容。'
        break
      case 'continue':
        prompt = `以下是文章的一部分内容，请继续写下去：\n\n${aiParams.value.selectedText}\n\n${aiParams.value.instruction || '请继续撰写，保持风格一致。'}`
        systemPrompt = '你是一位专业的文章撰写者，擅长根据已有内容继续创作。'
        break
      case 'improve':
        prompt = `请优化以下内容：\n\n${aiParams.value.selectedText}\n\n${aiParams.value.instruction || '请提高表达的专业性和流畅度，但保持原意不变。'}`
        systemPrompt = '你是一位专业的文字编辑，擅长优化和改进文章内容。'
        break
      case 'summarize':
        const articleContent = editorInstance.value ? editorInstance.value.getContent({ format: 'text' }) : ''
        prompt = `请为以下文章生成一个${aiParams.value.summaryLength || '中等长度'}的摘要：\n\n${articleContent}`
        systemPrompt = '你是一位专业的编辑，擅长提炼文章要点并生成准确的摘要。'
        break
      case 'custom':
        prompt = aiParams.value.customPrompt
        systemPrompt = '你是一位专业的文字助手，根据用户的指令处理文本内容。'
        break
      case 'templates':
        if (currentTemplate.value) {
          const result = await processTemplate()
          prompt = result.user_prompt
          systemPrompt = result.system_prompt
        }
        break
    }
    
    const result = await generateArticleContent({
      model_id: selectedModelId.value,
      system_prompt: systemPrompt,
      user_prompt: prompt
    })
    
    aiResult.value = result.content
  } catch (error) {
    console.error('AI 生成失败', error)
    ElMessage.error('AI 生成失败: ' + error.message)
  } finally {
    aiGenerating.value = false
  }
}

const processTemplate = async () => {
  try {
    const response = await processPromptTemplate(aiParams.value.templateId, templateVariables.value)
    return response
  } catch (error) {
    console.error('处理模板失败', error)
    ElMessage.error('处理模板失败: ' + error.message)
    throw error
  }
}

const insertAIResult = () => {
  if (!aiResult.value || !editorInstance.value) return
  
  switch (aiDialogMode.value) {
    case 'generate':
      editorInstance.value.setContent(aiResult.value)
      break
    case 'continue':
    case 'improve':
      editorInstance.value.selection.setContent(aiResult.value)
      break
    case 'summarize':
      const currentContent = editorInstance.value.getContent()
      editorInstance.value.setContent(`<h2>摘要</h2><p>${aiResult.value}</p><hr>${currentContent}`)
      break
    case 'custom':
    case 'templates':
      if (editorInstance.value.selection.getContent()) {
        editorInstance.value.selection.setContent(aiResult.value)
      } else {
        editorInstance.value.insertContent(aiResult.value)
      }
      break
  }
  
  aiDialogVisible.value = false
  ElMessage.success('内容已插入到编辑器')
}

const regenerateContent = () => {
  aiResult.value = ''
  generateWithAI()
}

const loadAIModels = async () => {
  try {
    const models = await fetchAIModels()
    aiModels.value = models.filter(model => model.is_active)
    
    if (aiModels.value.length > 0) {
      selectedModelId.value = aiModels.value[0].id
    }
  } catch (error) {
    console.error('加载 AI 模型失败', error)
    ElMessage.error('加载 AI 模型失败')
  }
}

const loadPromptTemplates = async () => {
  try {
    promptTemplates.value = await fetchPromptTemplates()
  } catch (error) {
    console.error('加载提示词模板失败', error)
    ElMessage.error('加载提示词模板失败')
  }
}

const setEditorInstance = (instance) => {
  editorInstance.value = instance
}

const selectedArticleTemplate = ref(null)

const previewReference = (index) => {
  if (!referenceContents.value[index]) {
    ElMessage.warning('没有可预览的内容')
    return
  }
  
  // 设置当前参考内容并显示对话框
  currentReference.value = referenceContents.value[index]
  referenceDialogVisible.value = true
}

// 添加使用参考标题的方法
const useReferenceTitle = (index) => {
  if (!referenceContents.value[index] || !referenceContents.value[index].title) {
    ElMessage.warning('没有可用的标题')
    return
  }
  
  // 将参考内容的标题设置为文章标题
  articleParams.value.title = referenceContents.value[index].title
  
  ElMessage.success('已使用参考文章标题作为标题')
}

// 添加检查特定特殊变量是否存在的函数
const hasSpecialVariable = (name) => {
  if (!selectedArticleTemplate.value || !selectedArticleTemplate.value.variables) {
    return false
  }
  
  return selectedArticleTemplate.value.variables.some(v => v.name === name)
}

onMounted(async () => {
  // 判断是否是编辑模式
  isEdit.value = route.name === 'EditArticle'
  
  console.log('组件挂载，准备初始化编辑器')
  
  // 使用 nextTick 确保 DOM 已经渲染
  await nextTick()
  
  // 初始化编辑器
  try {
    await initVditor()
    console.log('编辑器初始化成功')
    
    // 如果是编辑模式，加载文章
    if (isEdit.value) {
      await loadArticle(route.params.id)
    }
    
    startAutoSave()
    loadAIModels()
    loadPromptTemplates()
  } catch (err) {
    console.error('编辑器初始化失败:', err)
    ElMessage.error('编辑器初始化失败')
  }
})

onBeforeUnmount(() => {
  vditor?.destroy()
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
  }
})

defineExpose({
  setEditorInstance
})
</script>

<style scoped>
.editor-container {
  display: flex;
  gap: 24px;
  padding: 24px;
  height: calc(100vh - 120px);
  background-color: #f5f7fa;
}

.params-section {
  width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
  max-height: 100%;
  overflow-y: auto;
}

.params-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.ai-tools-card {
  margin-top: 0;
}

.params-title {
  margin: 0 0 20px;
  font-size: 18px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.ai-tools-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 16px;
}

.content-section {
  position: relative; /* 确保可以使用绝对定位 */
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
}

.editor-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.vditor-container {
  flex: 1;
  overflow: hidden;
}

.reference-item {
  margin-bottom: 12px;
}

.add-reference-btn {
  width: 100%;
  margin-top: 8px;
}

.generate-btn {
  width: 100%;
  margin-top: 16px;
}

.full-width {
  width: 100%;
}

:deep(.vditor) {
  border: none;
}

:deep(.vditor-toolbar) {
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}

:deep(.vditor-ir) {
  padding: 24px;
  font-size: 16px;
  line-height: 1.6;
}

:deep(.vditor-ir pre.vditor-reset) {
  background: #fff;
  padding: 24px;
}

:deep(.vditor-preview) {
  padding: 24px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append .el-button) {
  border: none;
  margin: 0;
}

.ai-generating {
  margin: 20px 0;
}

.ai-result {
  margin: 20px 0;
}

.ai-content {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.ai-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.ai-actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.reference-meta {
  color: #606266;
  font-size: 14px;
  margin-top: 8px;
}

.reference-url {
  color: #909399;
  font-size: 13px;
  word-break: break-all;
}

.reference-content {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin: 16px 0;
}

.reference-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: inherit;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.special-variables-info {
  margin-bottom: 16px;
}

.special-vars-list {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.special-vars-list li {
  margin-bottom: 4px;
}

.editor-loading-overlay {
  position: absolute;
  top: 60px; /* 编辑器头部的高度 */
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 10;
  padding: 20px;
}
</style> 